"""
公告模块序列化器
"""
from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Announcement


class AnnouncementUserSerializer(serializers.ModelSerializer):
    """公告创建人序列化器（简化版）"""
    
    class Meta:
        model = User
        fields = ['id', 'username', 'email']


class AnnouncementSerializer(serializers.ModelSerializer):
    """公告序列化器"""
    user = AnnouncementUserSerializer(read_only=True)
    user_id = serializers.IntegerField(write_only=True, required=False)
    
    class Meta:
        model = Announcement
        fields = ['id', 'title', 'content', 'time', 'user', 'user_id']
        read_only_fields = ['id', 'time']
    
    def create(self, validated_data):
        """创建公告，自动关联当前用户"""
        # 从context中获取当前用户
        request = self.context.get('request')
        if request and hasattr(request, 'user'):
            validated_data['user'] = request.user
        return super().create(validated_data)


class AnnouncementListSerializer(serializers.ModelSerializer):
    """公告列表序列化器（简化版）"""
    user_name = serializers.CharField(source='user.username', read_only=True)
    
    class Meta:
        model = Announcement
        fields = ['id', 'title', 'time', 'user_name']
